package cn.orange.ch01_array.binarysearch;

/**
 * LC704.二分查找
 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target
 写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1
 */
public class LC704 {
    /**
     * 二分法有两种写法
     * right = nums.length - 1;则循环条件为left <= right,则循环终止时left > right
     * right = nums.length;则循环条件为left < right,则循环终止时left = right
     */
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (target < nums[mid]) {
                right = mid - 1;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        LC704 alg = new LC704();
        System.out.println(alg.search(new int[]{-1, 0, 3, 5, 9, 12}, 9));
        System.out.println(alg.search(new int[]{-1, 0, 3, 5, 9, 12}, 2));
    }
}
